<script setup lang="ts">
import { MenuRoutes } from '@/router/routes'
import { useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'
import checkAccess from '@/access/checkAccess'
import { useLocalStorage } from '@vueuse/core'
import { fetchEventSource } from "@microsoft/fetch-event-source"
import { UserOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { ACCESS_ENUM } from '@/access/accessEnum'
import { type MenuProps, message } from 'ant-design-vue'
import ThemeSwitch from '@/ui/ThemeSwitch.vue'
import { safeJsonParse } from '@/utils/safeJson'
const router = useRouter()
const userStore = useUserStore()
const { id, username, avatar } = storeToRefs(userStore)
const { resetStore } = userStore
const AccessToken = useLocalStorage('access_token', null)
const RefreshToken = useLocalStorage('refresh_token', null)
const UserName = useLocalStorage('userName', '')
const Password = useLocalStorage('password', '')
router.afterEach((to, _from, _failure) => {
    selectedKeys.value = [to.path]
})
const selectedKeys = ref(['/'])
const visibleRoutes = MenuRoutes.filter((item, _index) => {
    return true
    // return checkAccess(role.value, (item?.meta?.access as number) ?? ACCESS_ENUM.USER)
})
const activeIndex = ref(0)
const items = ref<any>([])
visibleRoutes.forEach((route, index) => {
    items.value?.push({
        key: index,
        name: route.name,
        title: route.meta?.title as any || route.name,
        label: route.meta?.title as any || route.name
    })
})
const handleMenuClick: MenuProps['onClick'] = (e) => {
    if (e.key === '1') {
        message.success('退出登录')
        resetStore()
        AccessToken.value = null
        RefreshToken.value = null
        UserName.value = ''
        Password.value = ''
        router.push({ name: 'login' })
    } else if (e.key === '2') {
        router.push({ name: `account`, query: { uid: id.value } })
    } else if (e.key === '3') {
        router.push({ name: 'ide' })
    }
}
const data = ref(0)
onMounted(async () => {
    await fetchEventSource(`/api/chat/unread?id=${id.value}`, {
        headers: {
            Authorization: `${AccessToken.value}`
        },
        onmessage(event) {
            if (event.data === 'pong') return
            data.value = + safeJsonParse(event.data).value
        },
        onerror(event) {
            console.log('EventSource error:', event)
        },
        onclose() {
            console.log('EventSource closed:')
        },
        async onopen(res) {
            console.log('EventSource connected:', res)
        }
    })
})

</script>

<template>
    <div class="bg-white">
        <a-row :gutter="10" id="globalHeader" :wrap="false">
            <a-col :span="1">
                <div>
                    <img style="width: 50px; height: 50px;" src="@/assets/logo.svg" alt="XOJ Logo" />
                </div>
            </a-col>
            <a-col :span="18">
                <div>
                    <a-menu v-model:selectedKeys="activeIndex" mode="horizontal" :items="items" :ellipsis="false"
                        @select="(i) => $router.push({ name: i.item.name })" class="text-3xl leading-14 mt-3" style=" font-family: '楷体', sans-serif;
" />
                </div>
            </a-col>
            <a-col :span="2"></a-col>
            <a-col :span="1">
                <a-badge :count="data" :overflow-count="99">
                    <a-avatar size="large" :src="avatar" style="cursor: pointer"
                        @click="$router.push({ name: 'profile', query: { uid: id } })" />
                </a-badge>
            </a-col>
            <a-col :span="1" class="items-center" style="font-size-adjust: revert">
                <div>
                    <a-dropdown-button split-button type="primary"
                        @click="router.push({ name: 'personal-center', query: { uid: id } })">
                        {{ username }}
                        <template #overlay>
                            <a-menu @click="handleMenuClick">
                                <a-menu-item key="1">
                                    <UserOutlined />
                                    退出登录
                                </a-menu-item>
                                <a-menu-item key="2">
                                    <UserOutlined />
                                    个人信息
                                </a-menu-item>
                                <a-menu-item key="3">
                                    <UserOutlined />
                                    编辑器
                                </a-menu-item>
                            </a-menu>
                        </template>
                    </a-dropdown-button>
                </div>
            </a-col>
        </a-row>
    </div>
</template>

<style scoped>
#globalHeader {
    margin: 0 !important;
    justify-items: center;
    align-items: center;
}
</style>
